﻿using System.Text.Json.Serialization;
using BP.Plugin.Monitor.Application.Common.Interfaces;
using BP.Plugin.Monitor.Application.Features.OnlineUsers.DTOs;
using BP.Plugin.Monitor.Domain.Entities;
using Core.Attributes;
using Core.Extensions;
using Core.Interfaces.Users;
using Core.Models;
using Gridify;
using Gridify.EntityFramework;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BP.Plugin.Monitor.Application.Features.OnlineUsers.Queries.PaginationQuery;

[NoLogging]
public class OnlineUsersWithPaginationQuery : GridifyQuery, IRequest<PaginatedData<OnlineUserDto>>
{
    [JsonIgnore]
    public int Type { get; set; }
}

public class OnlineUsersWithPaginationQueryHandler :
         IRequestHandler<OnlineUsersWithPaginationQuery, PaginatedData<OnlineUserDto>>
{
    private readonly IMonitorDbContext _db;
    private readonly ICurrentUserService _currentUserService;

    public OnlineUsersWithPaginationQueryHandler(
        IMonitorDbContext db, ICurrentUserService currentUserService)
    {
        _db = db;
        _currentUserService = currentUserService;
    }

    public async Task<PaginatedData<OnlineUserDto>> Handle(OnlineUsersWithPaginationQuery request, CancellationToken cancellationToken)
    {
        var userId = _currentUserService.GetUserId();
        return (await _db.OnlineUsers
            .AsNoTracking()
            .WhereIf(request.Type == 0, x => x.IsOnline)
            .WhereIf(request.Type == 1|| request.Type == 2, x => x.UserId == userId && x.Status.HasValue)
            .GridifyAsync(request, cancellationToken))
            .ToPaginatedList<OnlineUser, OnlineUserDto>(request.Page, request.PageSize);
    }
}
